import { getClassCouponsByType, deleteClassCoupons, postClassCoupons } from '../../../services/api';

export default {
  namespace: 'coupons',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload: currentPage }, { call, put }) {
      const response = yield call(getClassCouponsByType, 'platform', currentPage);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *add({ payload, callback }, { call, put }) {
      const response = yield call(postClassCoupons, payload);
      yield put({
        type: 'append',
        payload: response,
      });
      if (callback) callback();
    },
    *remove({ payload, callback }, { call, put }) {
      const { id, currentIndex } = payload;
      yield call(deleteClassCoupons, id);
      yield put({
        type: 'delete',
        payload: currentIndex,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    append(state, action) {
      const { list } = state.data;
      list.unshift(action.payload);
      const total = state.data.pagination.total + 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
    delete(state, action) {
      const { list } = state.data;
      list.splice(action.payload, 1);
      const total = state.data.pagination.total - 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
  },
};
